package org.example.memora.Repository;

import lombok.RequiredArgsConstructor;
import org.example.memora.entity.ChatHistoryEntity;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@RequiredArgsConstructor
@Component
public class MongoChatHistoryRepository implements ChatHistoryRepository {

    private final MongoTemplate mongoTemplate;

    private static final String COLLECTION_NAME = "chat_history";

    @Override
    public void save(String type, String chatId) {
        Query query = new Query(Criteria.where("type").is(type).and("chatId").is(chatId));
        boolean exists = mongoTemplate.exists(query, ChatHistoryEntity.class, COLLECTION_NAME);
        if (!exists) {
            mongoTemplate.save(new ChatHistoryEntity(type, chatId), COLLECTION_NAME);
        }
    }

    @Override
    public List<String> getChatIds(String type) {
        Query query = new Query(Criteria.where("type").is(type));
        List<ChatHistoryEntity> histories = mongoTemplate.find(query, ChatHistoryEntity.class, COLLECTION_NAME);
        return histories.stream().map(ChatHistoryEntity::getChatId).toList();
    }
}

